import { ChangeDetectionStrategy, Component, Input, OnDestroy, OnInit } from '@angular/core';
import { DndService, DragSourceOptions } from '@ng-dnd/core';
import { BoxWithLocation } from './BoxWithLocation';
import { horseImage } from './horseImage';

@Component({
  selector: 'app-draggable-box',
  template: `
    <div class="draggable-box" [dragSourceOptions]="option" [dragSource]="source">
      <app-box [title]="name"></app-box>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DraggableBoxComponent implements OnInit, OnDestroy {
  @Input() id!: number;
  @Input() name!: string;
  @Input() type!: string;
  option: DragSourceOptions = { dropEffect: 'copy' };

  source = this.dnd.dragSource<BoxWithLocation>('BOX', {
    beginDrag: () => {
      const left = 30;
      const top = 30;
      const { id, name, type } = this;
      return { id, name, type, left, top };
    },
  });

  isDragging$ = this.source.listen(m => m.isDragging());

  constructor(private dnd: DndService) { }

  ngOnInit() {
    // this.source.connectDragPreview(getEmptyImage(), {
    //   // for ie11 compat with DragLayer
    //   captureDraggingState: true,
    // });
    const img = new Image();
    img.width = 100;
    img.height = 50;
    img.src = horseImage;
    img.onload = () => this.source.connectDragPreview(img);
  }

  ngOnDestroy() {
    this.source.unsubscribe();
  }
}
